import * as allIcons from '@ant-design/icons';
import RightContent from '@/components/RightContent';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from 'umi';
import { history, Link } from 'umi';
import defaultSettings from '../config/defaultSettings';
import { getUserInfoById as queryCurrentUser } from '@/services/groupNumber';
import './global.less';
import React from 'react';
import { getMenuList as queryMenu } from './services/menu';
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/loginByAccount';

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  menuData?: API.MenuListItem[];
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  fetchMenu?: (roleId: any) => Promise<API.MenuListItem[] | undefined>;
}> {
  let menuData: API.MenuListItem[] = [];
  const fetchUserInfo = async () => {
    try {
      const userId = sessionStorage.getItem('userId');
      if (!userId) {
        // history.push(loginPath);
        return;
      }
      const msg = await queryCurrentUser({
        id: userId,
      });
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  const fetchMenu = async (roleId: any) => {
    const params = {
      roleId: roleId,
    };
    const msg = await queryMenu(params);
    return msg.data;
  };
  const { location } = history;
  // 如果不是登录页面，执行
  if (location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    let menuData = [];
    if (!!currentUser?.roleId) {
      menuData = await fetchMenu(currentUser.roleId);
    }

    return {
      fetchUserInfo,
      fetchMenu,
      currentUser,
      menuData,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }
  return {
    fetchUserInfo,
    fetchMenu,
    menuData,
    settings: defaultSettings,
  };
}
// FIX从接口获取菜单时icon为string类型
const fixMenuItemIcon = (menus: [any], iconType = 'Outlined'): [any] => {
  menus?.forEach((item) => {
    const { icon, children } = item;
    if (typeof icon === 'string') {
      let fixIconName = icon.slice(0, 1).toLocaleUpperCase() + icon.slice(1) + iconType;
      item.icon = React.createElement(allIcons[fixIconName] || allIcons[icon]);
    }
    children && children.length > 0 ? (item.children = fixMenuItemIcon(children)) : null;
  });
  return menus;
};
// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    menuDataRender: () => fixMenuItemIcon(initialState?.menuData),
    rightContentRender: () => <RightContent />,
    // disableContentMargin: false,

    // footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      const userId = sessionStorage.getItem('userId');
      // 如果没有登录，重定向到 login
      console.log('跳转至：'+location.pathname);
      if (!userId && !initialState?.currentUser && ![loginPath,'/user/loginByAccount','/user/login'].indexOf(location.pathname)) {
        history.push(loginPath);
      }
    },

    menuHeaderRender: undefined,
    // 自定义 403 页面
    unAccessible: <div>无权限访问</div>,
    // 增加一个 loading 的状态
    childrenRender: (children: any) => {
      return <>{children}</>;
    },
    ...initialState?.settings,
  };
};
